package com.zq.widget.inverted.game.role.impl.prop;

import android.content.Context;
import android.view.animation.AnimationUtils;

import com.zq.widget.inverted.R;
import com.zq.widget.inverted.game.role.impl.base.DrawableRole;
import com.zq.widget.inverted.game.role.impl.type.Prop;

/**
 * Created by zhangqiang on 2018/4/2.
 */
public class PropRole extends DrawableRole implements Prop {

    private int degree, lastDegree;
    private long startTime,lastTime;
    private float velocity;
    private int count;
    private Object[] props;
    private long duration;

    public PropRole(Context context, float startX, float startY, float velocity, long duration, Object... prop) {
        super(context, R.drawable.wsparticle_41);
        this.velocity = velocity;
        this.duration = duration;
        this.count = prop == null ? 0 : prop.length;
        this.props = prop;
        updateLocation(startX,startY);
    }

    @Override
    public void preDraw() {
        super.preDraw();

        long timeMillis = AnimationUtils.currentAnimationTimeMillis();
        if (lastTime <= 0) {
            lastTime = timeMillis;
            degree = randomDegree();
        }

        long pastTime = timeMillis - lastTime;
        lastTime = timeMillis;

        float distance = (float) pastTime / 1000 * velocity;
        float dx, dy;
        double radians = Math.toRadians(degree);
        dx = (float) (Math.cos(radians) * distance);
        dy = -(float) (Math.sin(radians) * distance);
        locationOffset(dx, dy);
        if(isContactCanvasBounds()){
            degree = randomDegree();
        }
    }

    @Override
    public boolean isFinish() {

        long timeMillis = AnimationUtils.currentAnimationTimeMillis();
        if(startTime <= 0){
            startTime = timeMillis;
        }
        return super.isFinish() || count <= 0 || timeMillis - startTime > duration;
    }


    private int randomDegree() {

        int degree;
        if (lastDegree <= 0) {
            degree = (int) (Math.random() * 360);
        }else {
            degree = (int) ((lastDegree + 180 + (30 - Math.random() * 60)) % 360);
        }
        lastDegree = degree;
        return degree;
    }

    @Override
    public Object take() {

        if(count > 0){
            return props[--count];
        }
        return null;
    }
}
